//
//  ExtensionString.swift
//  StoreManage
//
//  Created by MC on 2017/12/18.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

extension String {
    
    //MD5加密
    func MCMD5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize(count: 0)
        
        return String(format: hash as String)
    }


    
    // 计算字符串的高度
    func MCString_getHeight(font:UIFont,width:CGFloat) -> CGFloat {
        let statusLabelText: NSString = self as NSString
        let size = CGSize.init(width: width, height: 9000)
        let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context: nil).size
        return strSize.height
    }
    
    // 计算字符串的宽度
    func MCString_getWidth(font:CGFloat,height:CGFloat) -> CGFloat {
        let statusLabelText: NSString = self as NSString
        let size = CGSize.init(width: 9999, height: height)
        let dic = NSDictionary(object: UIFont.systemFont(ofSize: font), forKey: NSAttributedStringKey.font as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context: nil).size
        return strSize.width
    }

    
    // 字符串的截取 从指定位置截取到指定index
    func MCString_prefixFromeBeginIndex(_ begin:Int,index:Int) -> String {
        if self.count < (index + begin) {
            return self
        } else {
            let beginIndex = self.index(self.startIndex, offsetBy: begin)

            let index = self.index(self.startIndex, offsetBy: begin + index)
            let str = self[beginIndex..<index]
            return String(str)
        }
    }
    
    
    // 字符串的截取 从头截取到指定index
    func MCString_prefix(index:Int) -> String {
    
        
        if self.count <= index {
            return self
        } else {
            let index = self.index(self.startIndex, offsetBy: index)
            let str = self.prefix(upTo: index)
            return String(str)
        }
    }
    /**
     * 字符串的截取 从指定位置截取到尾部
     */
    func MCString_suffix(index:Int) -> String {
        if self.count <= index {
            return self
        } else {            
            let selfIndex = self.index(self.startIndex, offsetBy: index)
            let str = self.suffix(from: selfIndex)
            return String(str)
        }
    }
    // 截取指定的区间
    func MCString_range(location:Int, length:Int) -> String {
        if location >= self.count {
            return ""
        }
        if location + length >= self.count {
            return self
        }
        let locationIndex = self.index(startIndex, offsetBy: location)
        let range = locationIndex..<self.index(locationIndex, offsetBy: length)
        return String(self[range])
    }
    
    
    
    
    
    
    
    
    // 设置文本的行间距
    public func MCAttributedString_lineSpace(lineSpace:CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = lineSpace
        let range = NSRange.init(location: 0, length: self.count)
        attributedString.addAttributes([NSAttributedStringKey.paragraphStyle:paragraphStyle], range: range)
        
        return attributedString
    }
    // 设置文本的颜色
    public func MCAttributedString_color(color:UIColor,range:NSRange) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        return attributedString
    }
    // 设置文本的字体大小
    public func MCAttributedString_font(font:CGFloat,range:NSRange) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: font), range: range)
        return attributedString
    }
    
    // NSStrikethroughStyleAttributeName
    // 设置删除线
    public func MCAttributedString_deleteLine(color:UIColor) -> NSAttributedString {
        let range = NSMakeRange(0, self.count)
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 1, range: range)
        return attributedString
    }

    
    public func MCAttributedString_textAttachment(text:String,image:UIImage,imageFrame:CGRect) -> NSMutableAttributedString {
    
        let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
        let nameStr : NSAttributedString = NSAttributedString(string: " " + text, attributes: nil)
        
        let attachment = NSTextAttachment.init()
        attachment.image = image
        attachment.bounds = imageFrame
        
        attributedStrM.append(NSAttributedString(attachment: attachment))
        attributedStrM.append(nameStr)
        return attributedStrM
    }
}

// 智能去掉小数点尾部的0
func MCString_judgemantDecimalsIsZero(figure:Int) -> String {
    let price = CGFloat(figure)
    let price1 = String(format: "%.2f", CGFloat(figure)/100)
    var price2 = String(format: "%.2f", CGFloat(figure)/100)
    
    let indexOne = price1.index(price1.endIndex, offsetBy: -1)
    let lastOne = price1.suffix(from: indexOne)
    
    let indexTwo = price1.index(price1.endIndex, offsetBy: -2)
    let lastTwo = price1.suffix(from: indexTwo)
    
    if lastOne == "0" { price2 = String.init(format: "%.1f", price/100) }
    if lastTwo == "00" { price2 = String.init(format: "%.0f", price/100) }
    
    // 有负数的情况
    if price2.contains("-") {
        let firstIndex = price2.index(price1.startIndex, offsetBy: 1)
        price2.insert("¥", at: firstIndex)
        return price2
    } else {
        return "¥" + price2
    }
}

// 判断是否电话号码 11位并且首位是1
public func MCString_judgemantPhoneNumberIsTrue(str:String) -> Bool {
    if str.count != 11 { return false }
    if str.first != "1" { return false }
    return true
}

// 对金额输入的控制
func MCString_keepTwoDecimalPlaces(_ textField:UITextField,_ range:NSRange,_ string:String) -> Bool {
    let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
    let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
    let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
    return numberOfMatches != 0
}


// 字典转字符串json
func MCString_createStrFromDictory(dictionary:NSDictionary) -> String {
    if (!JSONSerialization.isValidJSONObject(dictionary)) {
        print("无法解析出JSONString")
        return ""
    }
    let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
    let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
    return JSONString! as String
}

// 字符串转字典
func MCString_createDictionaryFromJSONString(jsonString:String) ->NSDictionary{
    
    let jsonData:Data = jsonString.data(using: .utf8)!
    
    let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
    if dict != nil {
        return dict as! NSDictionary
    }
    return NSDictionary()
}
